import axios from 'axios'
import utils from './utils'

const transformRequest = (data, headers) => {
  if (utils.isFormData(data) ||
    utils.isArrayBuffer(data) ||
    utils.isBuffer(data) ||
    utils.isStream(data) ||
    utils.isFile(data) ||
    utils.isBlob(data) ||
    utils.isArrayBufferView(data) ||
    utils.isURLSearchParams(data)
  ) {
    return data
  }
  if (utils.isObject(data)) {
    for (var pkey in data) {
      if (data[pkey] === null || typeof (data[pkey]) === 'undefined') {
        delete data[pkey]
      }
    }
    data = utils.params(data)
    return data
  }
  return data
}

axios.defaults.transformRequest.unshift(transformRequest)

const instance = axios.create({
  baseURL: process.env['BASE_URL'] || 'http://localhost:8080'
})

// request interceptor
instance.interceptors.request.use(config => {
  return config
}, error => {
  console.log(error)
  return Promise.reject(error)
})

// respone interceptor
instance.interceptors.response.use(response => {
  return response.data
}, error => {
  return Promise.reject(error.response.data)
})

export default instance
